package org.docshare.zhuishu;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;

import org.docshare.http.DataServer;
import org.docshare.http.YangResponse;

import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/5/14.
 */
public class FavFragment extends Fragment implements RefleshListView.IReflashListener, AdapterView.OnItemClickListener {
    RefleshListView favlist;

    private static final String TAG = "FavFragment";
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_fav,null,false);
        favlist = (RefleshListView) v.findViewById(R.id.favlist);

        favlist.setInterface(this);

        favlist.setOnItemClickListener(this);

        onReflash();
        return v;
    }
    private void initList(){
        Log.i(TAG, "initList: ");
        //设置主界面列表
        String[] sa = {"ddddd","www","www","www"};
        ArrayAdapter<String> aa = new ArrayAdapter<String>(this.getContext(),android.R.layout.simple_list_item_1,sa);
        favlist.setAdapter(aa);
    }
    JSONArray favdata;
    private void initList2(){
        String[] from = {"bookname","last_captitle"};
        int[] to = {R.id.bookname,R.id.captitle};
        Object o = favdata;
        SimpleAdapter adapter = new SimpleAdapter(this.getContext(), (List<? extends Map<String, ?>>)o, R.layout.item_fav,from,to);
        favlist.setAdapter(adapter);
    }

    @Override
    public void onReflash() {

        DataServer.getIns(this.getContext()).fav(new YangResponse() {
            @Override
            public void onResult(boolean succ, Object response) {
            Log.i(TAG, "onResult: "+response);
            if(response instanceof String){
            	Toast.makeText(FavFragment.this.getContext(), (String)response, Toast.LENGTH_LONG).show();
            	return;
            }
            favdata = (JSONArray) response;
            initList2();
            favlist.reflashComplete();
            }
        });

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        JSONObject fitem = null;
        try {
            fitem = favdata.getJSONObject((int) id);
            int bookid = fitem.getInteger("bookid");
            BookFragment f = new BookFragment(bookid);
            GlobalConfig.mainAcitivity.switchToFragment(f,true);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
